<!--个人信息与认证页面-->
<template>
  <div class="authentication">
    <!--tab切换-->
    <div class="authentication-tab">
      <div @click="checkoutNav(0)" class="authentication-tab-list" :class="{active:cur==0}">个人信息</div>
      <div
        v-if="userInfo && userInfo.companyType == -1"
        @click="checkoutNav(1)"
        class="authentication-tab-list"
        :class="{active:cur==1}"
      >认证</div>
    </div>
    <!-----个人信息----->
    <div class="authentication-user" v-show="cur==0">
      <div class="authentication-user-list">
        <el-form ref="form" label-width="100px">
          <el-form-item label="手机号">
            <el-input v-model="username" placeholder :disabled="true" style="cursor:pointer"></el-input>
          </el-form-item>
          <el-form-item label="姓名">
            <el-input v-model="name" placeholder :disabled="userInfo && userInfo.companyType != -1"></el-input>
          </el-form-item>
          <el-form-item label="性别">
            <el-select v-model="editForm.gender" placeholder="请选择性别">
              <el-option
                v-for="item in genderList"
                :key="item.id"
                :label="item.label"
                :value="item.id"
              ></el-option>
            </el-select>
            <!--<el-input v-model="gender" placeholder=""></el-input>-->
          </el-form-item>
          <el-form-item label="身份证">
            <el-input
              v-model="identity"
              placeholder
              :disabled="userInfo && userInfo.companyType != -1"
            ></el-input>
          </el-form-item>
          <el-form-item label="公司">
            <el-input v-model="companyName" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="个人头像" style="width: 450px;">
            <div class="authentication-user-head">
              <el-upload
                style="display: inline-block;"
                ref="uploadHead"
                :limit="1"
                :show-file-list="false"
                :action="'loadFile'"
                :http-request="importRatehead"
                accept="image/jpeg, image/jpg, image/png"
              >
                <img v-show="!headPortrait" src="../assets/images/addimg.png">
                <img v-show="headPortrait" :src="headPortrait?headPortrait:imgDefault">
              </el-upload>
              <span class="logo-sign">（点击修改头像）</span>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div class="authentication-user-item">
        <div class="authentication-user-bt">
          <el-button type="success" style="padding:12px 35px;" @click="editUserInfo">保存</el-button>
          <el-button
            type="danger"
            @click="cancelAuth"
            v-if="userInfo && userInfo.companyType != -1"
          >取消认证</el-button>
        </div>
      </div>
    </div>
    <!--认证-->
    <div class="authentication-info" v-show="cur==1">
      <div v-if="clerk">
        <div class="authentication-info-title">公司验证</div>
        <div class="authentication-info-list">
          <el-form ref="form" label-width="100px">
            <el-form-item label="公司名称">
              <el-input v-model="comForm.companyName" placeholder="请选择公司名称"></el-input>
              <!--<el-autocomplete v-model="companyL" :fetch-suggestions="getCompanyList" placeholder="请选择公司名称" @select="selectCompany" style="width: 200px;"></el-autocomplete>-->
            </el-form-item>
            <el-form-item label="账户类型">
              <el-input v-model="companyType" style="width: 200px;" disabled placeholder="未选择"></el-input>
            </el-form-item>
            <el-form-item label="公司识别码">
              <el-input v-model="comForm.identityCode" style="width: 200px;" placeholder="请输入公司识别码"></el-input>
            </el-form-item>
            <el-form-item label="社会信用代码">
              <el-input
                v-model="comForm.trustedCode"
                style="width: 200px;"
                placeholder="请输入公司社会信用代码"
              ></el-input>
            </el-form-item>
          </el-form>
        </div>
        <div class="authentication-info-bt">
          <el-button
            type="primary"
            style="padding: 12px 50px"
            @click="clerkclick"
            :disabled="nextShow"
          >验证</el-button>
          <el-button
            type="primary"
            style="padding: 12px 50px"
            @click="next"
            :disabled="!nextShow"
          >下一步</el-button>
        </div>
      </div>
      <div v-if="user">
        <div class="authentication-info-title">信息上传</div>
        <div class="authentication-info-list">
          <el-form ref="form" label-width="100px">
            <el-form-item label="真实姓名">
              <el-input v-model="userForm.name" style="width: 200px;" placeholder="请输入您的真实姓名"></el-input>
            </el-form-item>
            <el-form-item label="身份证号">
              <el-input v-model="userForm.identity" style="width: 200px;" placeholder="请输入您的身份证号"></el-input>
            </el-form-item>
            <el-form-item label="照片">
              <div class="authentication-info-photo">
                <div class="img-box">
                  <el-upload
                    style="display: inline-block;"
                    ref="uploadjust"
                    :limit="1"
                    :show-file-list="false"
                    :action="'loadFile'"
                    :http-request="importRatejust"
                    accept="image/jpeg, image/jpg, image/png"
                  >
                    <img src="../assets/images/just.png">
                  </el-upload>
                  <div class="img-info" v-if="justImg">
                    <img :src="justImg?justImg:imgDefault">
                    <div class="img-shadow">
                      <i class="el-icon-delete" @click="deleteImg('just')"></i>
                    </div>
                  </div>
                </div>
                <div class="img-box">
                  <el-upload
                    style="display: inline-block;"
                    ref="uploadback"
                    :limit="1"
                    :show-file-list="false"
                    :action="'loadFile'"
                    :http-request="importRateback"
                    accept="image/jpeg, image/jpg, image/png"
                  >
                    <img src="../assets/images/back.png">
                  </el-upload>
                  <div class="img-info" v-if="backImg">
                    <img :src="backImg?backImg:imgDefault">
                    <div class="img-shadow">
                      <i class="el-icon-delete" @click="deleteImg('back')"></i>
                    </div>
                  </div>
                </div>
              </div>
            </el-form-item>
          </el-form>
        </div>
        <div class="authentication-info-notes">
          注：
          <br>1. 需上传清晰的身份证正面、反面共2张照片
          <br>2. 照片不超过5MB，支持格式jpg，jpeg，png
        </div>
        <div class="authentication-info-bt">
          <el-button type="primary" style="padding: 12px 50px" @click="previousStep">上一步</el-button>
          <el-button type="primary" style="padding: 12px 50px" @click="validation">验证</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as userAPI from "@/api/user";
import * as publicAPI from "@/api/public";
export default {
  name: "authentication",
  data() {
    return {
      nextShow: false,
      clerk: true,
      user: false,
      cur: 0,
      companyType: "", //用户类型
      username: "", //用户名/手机号
      name: "", //姓名
      editForm: {
        gender: "", //性别
        headPortrait: "" //头像
      },
      //   修改密码
      changeForm: {
        oldPassword: "",
        password: ""
      },
      password: "",
      birthday: "", //生日
      identity: "", //身份证号
      companyName: "", //公司名
      serviceLimit: "", //服务期限
      headPortrait: "", //头像
      companyList: [], //匹配的公司列表
      companyL: "", //认证公司名称
      comObj: null, //选中的公司
      comForm: {
        companyName: "",
        identityCode: "",
        trustedCode: ""
      },
      userForm: {
        companyId: "",
        identityCode: "",
        trustedCode: "",
        name: "",
        identity: "",
        phone: "",
        identityFront: "",
        identityReverse: ""
      },
      justImg: "",
      backImg: "",
      userInfo: null,
      genderList: [
        {
          id: "1",
          label: "男"
        },
        {
          id: "2",
          label: "女"
        },
        {
          id: "0",
          label: "未知"
        }
      ]
    };
  },
  created() {},
  mounted() {
    this.getUserInfo();
  },
  // computed: {
  // 	companyType() {
  // 		var str = "";
  // 		if(this.comObj) {
  // 			switch(this.comObj.type) {
  // 				case "0":
  // 					str = "智选房屋本公司";
  // 					break;
  // 				case "1":
  // 					str = "开发商";
  // 					break;
  // 				case "2":
  // 					str = "资产管理公司";
  // 					break;
  // 				case "3":
  // 					str = "中介公司";
  // 					break;
  // 				default:
  // 					break;
  // 			}
  // 		}
  // 		return str;
  // 	}
  // },
  methods: {
    checkoutNav(type) {
      this.cur = type;
      if (type == 0) {
        this.getUserInfo();
      }
      if (type == 1) {
        this.getUserInfoList();
      }
    },
    getUserInfoList() {
      let user = JSON.parse(localStorage.getItem("userInfo"));
      console.log(user);
      /*
				userAPI.getUserInfoList({
					userId:user.userName
				}).then((res)=>{
					console.log(res)
				})
				*/
    },
    getUserInfo() {
      //获取个人信息
      this.userInfo = JSON.parse(localStorage.getItem("userInfo"));
      console.log(this.userInfo, "===获取个人信息===");
      userAPI.getUserInfo().then(res => {
        if (res.code == 200) {
          this.username = this.userInfo.userName;
          this.name = res.data.name;
          this.editForm.gender = res.data.gender;
          this.identity = res.data.identity;
          this.companyName = res.data.companyName;
          this.serviceLimit = res.data.serviceLimit;
          this.headPortrait = res.data.headPortrait;
          this.editForm.headPortrait = res.data.headPortrait;
        }
      });
    },
    //模糊获取公司列表
    getCompanyList(keyword, cb) {
      this.companyList = [];
      userAPI
        .getCompanyKey({
          companyName: keyword,
          num: "10"
        })
        .then(res => {
          console.log(res);
          if (Array.isArray(res.data)) {
            if (res.data.length > 0) {
              res.data.forEach(item => {
                this.companyList.push({
                  id: item.companyId,
                  value: item.companyName,
                  type: item.type
                });
              });
            } else {
              this.comObj = null;
              this.companyL = "";
              this.comForm.companyId = "";
              this.$message.warning("公司不存在");
            }
          }
          cb(this.companyList);
        });
    },
    //选择公司
    selectCompany(item) {
      this.comObj = item;
      this.comForm.companyId = item.id;
    },
    next() {
      this.clerk = false;
      this.user = true;
    },
    clerkclick() {
      //验证公司
      if (!this.comForm.companyName) {
        this.$message.warning("请输入您要验证的公司名称");
        return;
      }
      if (!this.comForm.identityCode) {
        this.$message.warning("请输入10位公司识别码");
        return;
      } else if (
        this.comForm.identityCode.length != 10
      ) {
        this.$message.warning("请输入10位公司识别码");
        return;
      }
      if (!this.comForm.trustedCode) {
        this.$message.warning("请输入公司社会信用代码");
        return;
      }
      userAPI
        .companyAuth(this.comForm)
        .then(res => {
          if (res.code == "200") {
            this.nextShow = true;
            this.companyType = res.data.typeName;
            this.userForm.companyId = res.data.companyId;
            this.userForm.identityCode = this.comForm.identityCode;
            this.userForm.trustedCode = this.comForm.trustedCode;
            this.$message.success("公司认证成功，请继续个人信息认证");
          }
        })
        .catch(err => {
          this.$message.warning("公司验证失败，请检查是否填写正确");
        });
    },
    previousStep() {
      //上一步
      this.clerk = true;
      this.user = false;
    },
    importRatehead(item) {
      //处理上传头像
      //console.log(this.editForm,'=====性别====')
      //console.log(item,'====头像===')
      let formData = new FormData();
      formData.append("file", item.file);
      formData.append("width", 100);
      formData.append("height", 100);
      formData.append("water", 0);
      publicAPI.uploadImage(formData).then(res => {
        this.editForm.headPortrait = res.data.id;
        this.headPortrait = res.data.url;
      });
      this.$refs.uploadHead.clearFiles();
    },
    importRatejust(item) {
      //处理上传的人面像
      //console.log(item)
      let formData = new FormData();
      formData.append("file", item.file);
      formData.append("width", 179);
      formData.append("height", 107);
      formData.append("water", 1);
      userAPI.uploadImage(formData).then(res => {
        this.justImg = res.data.url;
        this.userForm.identityFront = res.data.id;
        console.log(res, "===处理上传的人面像==");
      });
    },
    importRateback(item) {
      //处理上传的非人面像
      //console.log(item)
      let formData = new FormData();
      formData.append("file", item.file);
      formData.append("width", 179);
      formData.append("height", 107);
      formData.append("water", 1);
      userAPI.uploadImage(formData).then(res => {
        this.userForm.identityReverse = res.data.id;
        this.backImg = res.data.url;
        console.log(res, "===处理上传的非人面像==");
      });
    },
    deleteImg(type) {
      //删除上传的图片
      console.log(type);
      if (type == "just") {
        this.$refs.uploadjust.clearFiles();
        this.userForm.identityFront = "";
        this.justImg = "";
      }
      if (type == "back") {
        this.$refs.uploadback.clearFiles();
        this.userForm.identityReverse = "";
        this.backImg = "";
      }
    },
    editUserInfo() {
      //修改个人信息
      console.log(this.editForm, "======修改个人信息=====");
      let obj = new Object(null);
      obj.gender = this.editForm.gender;
      obj.identity = this.identity;
      obj.name = this.name;
      if (this.editForm.headPortrait) {
        const index = this.editForm.headPortrait.indexOf("image/");
        if (index >= 0) {
          obj.headPortrait = this.editForm.headPortrait.substr(index+6);
        }else{
          obj.headPortrait = this.editForm.headPortrait;

        }
      }
      userAPI.updateUser(obj).then(res => {
        if (res.code == 200) {
          this.$message.success("修改成功");
        }
        this.getUserInfo();
      });
    },
    //取消认证
    cancelAuth() {
      this.$confirm(
        "取消认证后将清空发布的房源与创建的楼书，是否确认？",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).then(response => {
        this.$confirm(
          "发布的房源与楼书清空后将不可恢复！是否确认",
          "再次确认",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
        ).then(() => {
          userAPI.cancelAuth().then(response => {
            this.$message.success(response.message);
            const token = response.data.token;
            this.$cookies.set("signature",token,60*60*4);
            localStorage.userInfo = JSON.stringify(response.data);
            this.getUserInfo();
            setTimeout(() => {
              this.$router.go(0);
            }, 1500);
          });
        });
      });
      //console.log(this.userInfo)
    },
    validation() {
      //验证
      const idCard = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
      const phone = /^1[3456789]\d{9}$/;
      if (!this.userForm.name) {
        this.$message.warning("请输入您的真实姓名！");
        return;
      }
      if (!this.userForm.identity) {
        this.$message.warning("请输入身份证号！");
        return;
      } else if (!idCard.test(this.userForm.identity)) {
        this.$message.warning("身份证号格式不正确！");
        return;
      }
      //   if (!this.userForm.phone) {
      //     this.$message.warning("请输入注册手机号！");
      //     return;
      //   } else if (!phone.test(this.userForm.phone)) {
      //     this.$message.warning("手机号格式不正确！");
      //     return;
      //   }
      if (!this.userForm.identityFront) {
        this.$message.warning("请上传身份证正面图片！");
        return;
      }
      if (!this.userForm.identityReverse) {
        this.$message.warning("请上传身份证反面图片");
        return;
      }
      //console.log(this.userForm)
      userAPI
        .userAuth(this.userForm)
        .then(response => {
          this.cur = 0;
          this.clerk = true;
          this.user = false;
          const token = response.data.token;
          this.$cookies.set("signature",token,60*60*4);
          localStorage.setItem("userInfo", JSON.stringify(response.data));
          this.getUserInfo();
          this.$message.success(response.message);
          setTimeout(() => {
            this.$router.go(0);
          }, 2000);
        })
        .catch(err => {
          this.$message.warning(response.message);
        });
    }
  }
};
</script>
<style scoped>
.authentication {
  padding: 25px;
  height: auto;
  overflow: auto;
}
/*个人信息tab切换*/

.authentication-tab {
  display: flex;
}

.authentication-tab .active {
  background: #ffffff;
  color: #009fe8;
}

.authentication-tab-list {
  cursor: pointer;
  width: 150px;
  background: #f2f4f6;
  color: #778ca2;
  font-size: 14px;
  height: 40px;
  line-height: 40px;
  text-align: center;
}
/*个人信息*/

.authentication-user {
  background: #ffffff;
  padding: 50px 30px;
}

.authentication-user-list {
  width: 300px;
}

.authentication-user-item {
  /* display: flex; */
}

.authentication-user-bt {
  margin-left: 50px;
}

.authentication-user-head {
  height: 100px;
  display: flex;
  align-content: center;
  align-items: center;
}
.authentication-user-head .logo-sign {
  font-size: 12px;
  color: #999;
}
.authentication-user-head div .el-upload img {
  width: 100px;
  height: 100px;
  border: 1px dashed #ccc;
  border-radius: 5px;
}
/*认证*/

.authentication-info {
  background: #ffffff;
  padding: 50px 30px;
}

.authentication-info-title {
  color: #778ca2;
  font-size: 14px;
}

.authentication-info-tab {
  border: 1px solid #ebeef5;
  border-bottom: none;
  margin-top: 30px;
  margin-bottom: 30px;
}

.authentication-info-list {
  width: 300px;
  margin-top: 30px;
}

.authentication-info-bt {
  display: flex;
  justify-content: center;
  margin-bottom: 35px;
}

.authentication-info-notes {
  color: #778ca2;
  font-size: 10px;
  line-height: 25px;
  margin-bottom: 20px;
}

.authentication-info-photo {
  display: flex;
}

.authentication-info-photo .img-box {
  margin-right: 25px;
  width: 125px;
  height: 90px;
  position: relative;
}

.authentication-info-photo .img-box .el-upload img {
  width: 125px;
  height: 90px;
  border: 1px solid #e8ecef;
}

.authentication-info-photo .img-box .img-info {
  border-radius: 3px;
  position: absolute;
  border: 0 none;
  background: white;
  width: 125px;
  height: 90px;
  left: 0;
  top: 0;
}

.authentication-info-photo .img-box .img-info img {
  height: 100%;
  width: 100%;
  border-radius: 3px;
}

.authentication-info-photo .img-box .img-info .img-shadow {
  height: 100%;
  width: 100%;
  position: absolute;
  left: 0;
  top: 0;
  background: rgba(0, 0, 0, 0.2);
  color: #fff;
  text-align: center;
  line-height: 80px;
  font-size: 20px;
  display: none;
}

.authentication-info-photo .img-box .img-info .img-shadow i {
  cursor: pointer;
}

.authentication-info-photo .img-box .img-info:hover .img-shadow {
  display: block;
}

/deep/ .el-form-item__label {
  text-align: left;
}
</style>
<style>
.el-input input {
  cursor: default !important;
}
</style>
